﻿//-----------------------------------------------------------------------
//  This file is part of the Microsoft Code Samples.
// 
//  Copyright (C) Microsoft Corporation.  All rights reserved.
// 
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//-----------------------------------------------------------------------

#region Using directives

using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer;
using Microsoft.SqlServer.MessageBox;

#endregion

namespace Microsoft.Samples.SqlServer
{
    partial class EditOrder : Form
    {
        private AdventureWorksLocalDataSet adventureWorksLocalDataSet;
        private BindingSource salesOrderHeaderBindingSource;
        private BindingSource statusTextBindingSource;
        private bool newRecord;

        /// <summary>
        /// Edit Order form constructor
        /// </summary>
        /// <param name="awld"></param>
        /// <param name="salesOrderHeaderBindingSource"></param>
        /// <param name="statusTextBindingSource"></param>
        /// <param name="newRec"></param>
        public EditOrder(AdventureWorksLocalDataSet awld, BindingSource salesOrderHeaderBindingSource, BindingSource statusTextBindingSource, bool newRec)
        {
            InitializeComponent();

            this.adventureWorksLocalDataSet = awld;
            this.salesOrderHeaderBindingSource = salesOrderHeaderBindingSource;
            this.statusTextBindingSource = statusTextBindingSource;
            this.newRecord = newRec;
        }

        /// <summary>
        /// Add a new row to the Sales Detail Data Grid.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void AddButton_Click(object sender, EventArgs e)
        {
            int newRowIndex;

            try
            {
                //this.salesOrderDetailDataGridView.ClearSelection();

                // Get last row
                newRowIndex = this.salesOrderDetailDataGridView.Rows.Count - 1;

                // Select the new row 
                this.salesOrderDetailDataGridView.Rows[newRowIndex].Selected = true;

                // move the current cell to the new location
                this.salesOrderDetailDataGridView.CurrentCell
                    = this.salesOrderDetailDataGridView.Rows[newRowIndex].Cells["ProductNumber"];
                this.salesOrderDetailDataGridView.Rows[newRowIndex].Cells["ProductNumber"].ReadOnly = false;
                this.salesOrderDetailDataGridView.Focus();

                this.UpdateControls();
            }
            catch (Exception ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex,
                    ExceptionMessageBoxButtons.OK);
                emb.Show(this);
            }
        }

        /// <summary>
        /// Delete the currently selected row in the Sales Detail Data Grid.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void DeleteButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.salesOrderDetailDataGridView.SelectedRows.Count > 0)
                {
                    if (MessageBox.Show(this, Properties.Resources.AreYouSure,
                        Properties.Resources.DeleteProduct, MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, 0)
                        == DialogResult.Yes)
                    {
                        this.salesOrderDetailDataGridView.Rows.Remove(
                            this.salesOrderDetailDataGridView.SelectedRows[0]);

                        this.UpdateControls();
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex,
                    ExceptionMessageBoxButtons.OK);
                emb.Show(this);
            }
        }

        /// <summary>
        /// Save the users changes and hide the form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void SaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Save the edits to the dataset
                this.salesOrderHeaderBindingSource.EndEdit();
            }
            catch (Exception ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex,
                    ExceptionMessageBoxButtons.OK);
                emb.Show(this);
            }

            this.Hide();
        }

        /// <summary>
        /// Cancel the edit, do not save the changes and hide the form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void CancelButton_Click(object sender, EventArgs e)
        {
            CloseForm();
        }

        /// <summary>
        /// Setup the data bindings to allow us to edit the sales order 
        /// header and detail information.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void EditOrder_Load(object sender, EventArgs e)
        {
            try
            {
                this.PONumberTextbox.DataBindings.Add("Text",
                    this.salesOrderHeaderBindingSource, "PurchaseOrderNumber",
                    true);
                this.SubTotalTextbox.DataBindings.Add("Text",
                    this.salesOrderHeaderBindingSource, "SubTotal", true);
                this.TaxAmtTextbox.DataBindings.Add("Text",
                    this.salesOrderHeaderBindingSource, "TaxAmt", true);
                this.FreightTextbox.DataBindings.Add("Text",
                    this.salesOrderHeaderBindingSource, "Freight", true);
                this.OrderDateTextbox.DataBindings.Add("Text",
                    this.salesOrderHeaderBindingSource, "OrderDate", true);

                this.StatusComboBox.DataSource = this.statusTextBindingSource;
                this.StatusComboBox.DisplayMember = "StatusText";
                this.StatusComboBox.ValueMember = "StatusID";

                this.ShipDateTextbox.DataBindings.Add("Text",
                    this.salesOrderHeaderBindingSource, "ShipDate", true);
                this.CommentTextbox.DataBindings.Add("Text",
                    this.salesOrderHeaderBindingSource, "Comment", true);
                this.ModifiedDateTextbox.DataBindings.Add("Text",
                    this.salesOrderHeaderBindingSource, "ModifiedDate", true);
                this.TotalDueTextbox.DataBindings.Add("Text",
                    this.salesOrderHeaderBindingSource, "TotalDue", true);

                this.salesOrderDetailDataGridView.DataMember =
                    "FK_uspSalesOrderHeaderSelectCommand_uspSalesOrderDetailSelectCommand";
                this.salesOrderDetailDataGridView.DataSource
                    = this.salesOrderHeaderBindingSource;

                // Hide the SalesOrderId and SalesOrderDetailId columns
                this.salesOrderDetailDataGridView.Columns[
                    "SalesOrderID"].Visible = false;
                this.salesOrderDetailDataGridView.Columns[
                    "SalesOrderDetailID"].Visible = false;

                // Set the column properties.
                this.salesOrderDetailDataGridView.Columns[
                    "ProductNumber"].Width = 90;
                this.salesOrderDetailDataGridView.Columns[
                    "ProductNumber"].HeaderText = "Product ID";
                this.salesOrderDetailDataGridView.Columns[
                    "ProductNumber"].ReadOnly = false;

                this.salesOrderDetailDataGridView.Columns[
                    "Name"].Width = 150;
                this.salesOrderDetailDataGridView.Columns[
                    "Name"].HeaderText = "Product Name";
                this.salesOrderDetailDataGridView.Columns[
                    "Name"].ReadOnly = true;

                DataGridViewCellStyle rightAlignmentDataGridViewCellStyle
                    = new DataGridViewCellStyle();
                rightAlignmentDataGridViewCellStyle.Alignment
                    = DataGridViewContentAlignment.MiddleRight;

                this.salesOrderDetailDataGridView.Columns[
                    "UnitPrice"].Width = 80;
                this.salesOrderDetailDataGridView.Columns[
                    "UnitPrice"].HeaderText = "Unit Price";
                this.salesOrderDetailDataGridView.Columns[
                    "UnitPrice"].ReadOnly = true;
                this.salesOrderDetailDataGridView.Columns[
                    "UnitPrice"].DefaultCellStyle
                    = rightAlignmentDataGridViewCellStyle;

                this.salesOrderDetailDataGridView.Columns[
                    "OrderQty"].Width = 80;
                this.salesOrderDetailDataGridView.Columns[
                    "OrderQty"].HeaderText = "Quantity";
                this.salesOrderDetailDataGridView.Columns[
                    "OrderQty"].ReadOnly = false;
                this.salesOrderDetailDataGridView.Columns[
                    "OrderQty"].DefaultCellStyle
                    = rightAlignmentDataGridViewCellStyle;

                this.salesOrderDetailDataGridView.Columns[
                    "Description"].Width = 250;
                this.salesOrderDetailDataGridView.Columns[
                    "Description"].HeaderText = "Description";
                this.salesOrderDetailDataGridView.Columns[
                    "Description"].ReadOnly = true;

                if (this.newRecord)
                {
                    this.Text = Properties.Resources.NewOrder;

                    this.salesOrderHeaderBindingSource.AddNew();
                    AdventureWorksLocalDataSet.uspSalesOrderHeaderSelectCommandRow salesOrderHeaderRow =
                        (Microsoft.Samples.SqlServer.AdventureWorksLocalDataSet.uspSalesOrderHeaderSelectCommandRow)
                        ((System.Data.DataRowView)this.salesOrderHeaderBindingSource.Current).Row;
                    salesOrderHeaderRow.OrderDate = DateTime.Now;
                    salesOrderHeaderRow.DueDate = DateTime.Now.AddDays(21);
                    salesOrderHeaderRow.Status = 1; // In-Process
                    salesOrderHeaderRow.OnlineOrderFlag = false;
                    salesOrderHeaderRow.SubTotal = 0;
                    salesOrderHeaderRow.TaxAmt = 0;
                    salesOrderHeaderRow.Freight = 0;
                    salesOrderHeaderRow.ModifiedDate = DateTime.Now;
                    this.salesOrderHeaderBindingSource.EndEdit();
                }
                else
                {
                    this.Text = Properties.Resources.EditOrder;
                }

                this.UpdateControls();
            }
            catch (Exception ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex,
                    ExceptionMessageBoxButtons.OK);
                emb.Show(this);
            }
        }

        private void EditOrder_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                CloseForm();
            }
        }

        /// <summary>
        /// Watch for the current selection in the data drid view to change.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void salesOrderDetailDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            this.UpdateControls();
        }

        /// <summary>
        /// Enable or disable the controls based on whether there is a current 
        /// sales order detail grid selection.
        /// </summary>
        private void UpdateControls()
        {
            if (this.salesOrderDetailDataGridView.SelectedRows.Count > 0)
            {
                this.DeleteButton.Enabled = true;
            }
            else
            {
                this.DeleteButton.Enabled = false;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void CloseForm()
        {
            try
            {
                // Cancel the current edits
                this.salesOrderHeaderBindingSource.CancelEdit();

                this.adventureWorksLocalDataSet.RejectChanges();
            }
            catch (Exception ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex,
                    ExceptionMessageBoxButtons.OK);
                emb.Show(this);
            }

            this.Hide();
        }
    }
}
